﻿using BaseAuthRole.Domain.OutPut;
using BaseAuthRole.DTO.Auth;
using BaseAuthRole.IRepository;
using BaseAuthRole.IService;
using FreeSql;
using RS.BaseModel.Common;
using RS.BaseModel.Enum;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace BaseAuthRole.Service
{
    public class ApplicationService: IApplicationService
    {
        IAuthRepository _authRepository;

        private readonly UnitOfWorkManager _unitOfWorkManager;
        public ApplicationService(IAuthRepository authRepository, UnitOfWorkManager unitOfWorkManager) {

            _authRepository = authRepository;

            _unitOfWorkManager = unitOfWorkManager;


        }
        /// <summary>
        /// 创建应用并创建应用对应权限
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public int AddApplication(ApplicationModel model)
        {
            var r = 0;
            using (var trans = _unitOfWorkManager.Begin())
            {
                 r += this._authRepository.Orm.Insert(model).ExecuteAffrows();

                 r +=this._authRepository.Orm.Insert(new BaseAuthRole.DTO.Role.Action
                { 
                     ActionGroupId="1",
                     Id=model.Id,
                     ActionName=model.Name,
                      Status= model.Status,
                       Type=2,
                         UniqueId=model.UniqueId                                
                }).ExecuteAffrows();
            }
            return r;
        }

        public CommonResult CheckApp(string appid, string secret) {

            var result = new CommonResult();            

            var app = this._authRepository.Orm.Select<ApplicationModel>(new { Id = appid }).ToOne();

            if (app == null)
            {
                result.Value = EnumBaseResult.NoResource;
                result.Message = "无效的AppId";
                return result;
            }

            if (app.Secret != secret)
            {
                result.Value = EnumBaseResult.InvalidSecret;
                result.Message = "无效的密钥";
                return result;
            }
            if (app.Status != 1)
            {
                result.Value = EnumBaseResult.InvalidSecret;
                result.Message = "该应用已停用";
            }

            result.IsError = false;
            


            return result;

        }

        public CommonResult<GetAppAccessTokenModelOutPut> GetAppAccessTokenModel(string appid, string secret)
        {
            var result = new CommonResult<GetAppAccessTokenModelOutPut>();

            var app = this._authRepository.Orm.Select<ApplicationModel>(new { Id = appid }).ToOne();

            if (app == null)
            {
                result.Value = EnumBaseResult.NoResource;
                result.Message = "无效的AppId";
                return result;
            }

            if (app.Secret != secret)
            {
                result.Value = EnumBaseResult.InvalidSecret;
                result.Message = "无效的密钥";
                return result;
            }
            if (app.Status != 1)
            {
                result.Value = EnumBaseResult.InvalidSecret;
                result.Message = "该应用已停用";
            }
            var app_accesstoken = new AppAccessTokenModel
            {
                AppId = appid
            };

            var r = this._authRepository.Orm.Insert(app_accesstoken).ExecuteAffrows();

            if (r > 0)
            {
                result.IsError = false;
                result.Result = new GetAppAccessTokenModelOutPut
                {
                    AppAccessToken = app_accesstoken.AppAccessToken,
                    ExpireTime = app_accesstoken.ExpireTime,
                };
                return result;
            }
            else
            {
                result.Value = EnumBaseResult.SystemError ;
                result.Message = "系统错误";
                return result;
            }
        }

        [Obsolete]
        public AppAccessTokenModel GetAppAccessTokenModel(string appAccessToken)
        {
         
            var info = _authRepository.Orm.Select<AppAccessTokenModel>(new { AppAccessToken = appAccessToken }).ToOne();

            return info;

        }

        public ApplicationModel GetApplicationModel(string appid)
        {
            var info = this._authRepository.Orm.Select<ApplicationModel>(new { Id=appid}).ToOne();
            return info;
        }

        public IEnumerable<ApplicationModel> GetApplicationModel(int pagenum, int pagesize, string condition, string orderby, out long count, object para = null)
        {
            var sql= this._authRepository.Orm.Select<ApplicationModel>().Where(condition, para).OrderBy(orderby).Count(out count).Page(pagenum, pagesize).ToSql();
            var info=this._authRepository.Orm.Select<ApplicationModel>().Where(condition,para).OrderBy(orderby).Count(out count).Page(pagenum,pagesize).ToList();
            
            return info;

        }

        public int UpdateApplicationModel(ApplicationModel model)
        {          
            var r = 0;
            using (var trans =  _unitOfWorkManager.Begin())
            {
                r += this._authRepository.Orm.Update<ApplicationModel>().SetSource(model).ExecuteAffrows();

                r += this._authRepository.Orm.Update<BaseAuthRole.DTO.Role.Action>().SetSource(new BaseAuthRole.DTO.Role.Action
                {
                    ActionGroupId = "1",
                    Id = model.Id,
                    ActionName = model.Name,
                    Status = model.Status,
                    Type = 2,
                    UniqueId = model.UniqueId
                }).ExecuteAffrows();
            }
            return r;

        }

        public int DeleteApplicationModel(string id) {
            var r = 0;
            using (var trans =  _unitOfWorkManager.Begin())
            {
                r += this._authRepository.Orm.Delete<ApplicationModel>(new { Id=id}).ExecuteAffrows();

                r += this._authRepository.Orm.Delete<BaseAuthRole.DTO.Role.Action>(new { Id = id }).ExecuteAffrows();

            }
            return r;

        }


    }
}
